package XMLCreator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class XMLSpliter {
	public static long splitXMLBy(String fileIn,String filesOutStart,String filesOutEnd,int maxInFile,String forWhatToSplit,long firstFile){
		
		long countFile=firstFile;
		boolean inSamthing=false;
		int indexInFile=0;
		String line;
		
		try {
			File in=new File(fileIn);
			BufferedReader buf=new BufferedReader(new FileReader(in));
			File out=new File(filesOutStart+countFile+filesOutEnd);
			countFile++;
			FileWriter writer=new FileWriter(out);
			writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<all>\n");
			line=buf.readLine();
			while (line!=null){
//				line=ToAscii.fixString(line);
				if (inSamthing){
					int a=line.indexOf("</"+forWhatToSplit+">");
					if (a!=-1){
						writer.write(line.substring(0,a+forWhatToSplit.length()+3)+"\n");
						inSamthing=false;
						indexInFile++;
					}
					else{
						writer.write(line+"\n");
					}
				}
				else{
					int a=line.indexOf("<"+forWhatToSplit+">");
					if (a!=-1){
						writer.write(line.substring(a)+"\n");
						inSamthing=true;
					}
				}
				
				if (indexInFile==maxInFile){
					writer.write("</all>");
					writer.close();
					out=new File(filesOutStart+countFile+filesOutEnd);
					countFile++;
					indexInFile=0;
					writer=new FileWriter(out);
					writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<all>\n");
				}
				
				line=buf.readLine();
			}//end while
			
			writer.write("</all>");
			writer.close();
			return countFile;
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}
}
